package lomasky.ma.httpUtils;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;


import com.saifan.wyy_ov.config.Api;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author loma
 * @Description: 基于okHttp的网络请求工具
 * @date: 2016/6/1 11:37
 * @version: V1.0
 */
public class HttpUtil {
    //    /**
//     * 赛帆演示版本
//     */

//    public static String URL_IP = "";
//    public static String URL_ROOT = URL_IP+"/api/Customer";

    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");


    public static void post(final Activity context, final String api, Map<String, Object> map, String tip, final ICallBack callBack) {

        if (TextUtils.isEmpty(Api.getUrlIp())) {
            callBack.err("404");
            return;
        }

        KLog.json(map.toString());
        ProgressDialogUtil.showProgressDialog(context, false, tip);

        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        final String json = JsonUtil.toJson(map);
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json);
        //创建一个请求对象
        Request request = new Request.Builder()
                .url(Api.getUrlRoot() + api)
                .post(requestBody)
                .build();
        //发送请求获取响应
        getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                KLog.e(e);
                e.printStackTrace();
                ProgressDialogUtil.closeProgressDialog();
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callBack.err(e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ProgressDialogUtil.closeProgressDialog();
                final String string = response.body().string();
                KLog.d("返回数据" + api);
                KLog.d(string);
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            JSONObject jsonObject = new JSONObject(string);
                            int code = jsonObject.getInt("Code");
                            String content = jsonObject.getString("Content");
                            ResponseBean responseBean = new ResponseBean(api, code, content);
                            callBack.ok(responseBean);

                        } catch (JSONException e) {
                            e.printStackTrace();

                            callBack.err("请求错误");
                        }

                    }
                });


            }
        });


    }

    static OkHttpClient client;

    @NonNull
    private static OkHttpClient getClient() {
        if (client == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            client = builder.connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS).retryOnConnectionFailure(true).build() ;
        }

        return client;
    }

    public static void post(final Activity context, final String api, Map<String, Object> map, final ICallBack callBack) {

        if (TextUtils.isEmpty(Api.getUrlIp())) {
            callBack.err("404");
            return;
        }


        KLog.json(map.toString());

        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        final String json = JsonUtil.toJson(map);
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json);
        //创建一个请求对象
        Request request = new Request.Builder()
                .url(Api.getUrlRoot() + api)
                .post(requestBody)
                .build();
        //发送请求获取响应
        getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                KLog.e(e.toString());
                e.printStackTrace();
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callBack.err(e.getLocalizedMessage());
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();


                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            JSONObject jsonObject = new JSONObject(string);
                            int code = jsonObject.getInt("Code");
                            String content = jsonObject.getString("Content");
                            ResponseBean responseBean = new ResponseBean(api, code, content);
                            callBack.ok(responseBean);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            callBack.err("请求错误");
                        }

                    }
                });


            }
        });


    }


    public static void check(final Activity activity, final Map<String, Object> map, final ICallBack callBack) {


        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

        final String key = map.get("action").toString();
        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        final String json = new org.json.JSONObject(map).toString();
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json);
        KLog.json(json);
        //创建一个请求对象
        Request request = new Request.Builder()
                .url("http://master.sfwyy.com/Ajax/InterFace.ashx")
                .post(requestBody)
                .build();

        getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callBack.err(e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {


                try {
                    org.json.JSONObject jsonObject = new org.json.JSONObject(response.body().string());
                    boolean result = jsonObject.getBoolean("Result");
                    String msg = jsonObject.getString("Message");
                    String data = jsonObject.getString("Content");
                    int code = jsonObject.getInt("Code");
                    KLog.json(jsonObject.toString());
                    final ResponseBean responseBean=       new ResponseBean(result, msg, data.toString(), code, key);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            callBack.ok(responseBean);
                        }
                    });



                } catch (final  Exception e) {
                    e.printStackTrace();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            callBack.err(e.getMessage());
                        }
                    });
                }



            }
        });
    }


    public static void checkVesionNoDialog(String name, Callback callback) {

        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)

        JSONObject jsonObject = new org.json.JSONObject();
        try {
            jsonObject.put("Name", name);
            jsonObject.put("Type", "android");
        } catch (org.json.JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, jsonObject.toString());
        //创建一个请求对象
        Request request = new Request.Builder()
                .url("http://www.sfwyy.com/api/api/appversion")
                .post(requestBody)
                .build();

        getClient().newCall(request).enqueue(callback);
    }

}
